/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.freemarker;

import java.io.IOException;
import java.io.Writer;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author: libo Date: 17-3-1 Time: 下午12:13
 * @version: \$Id$
 */
public class OverrideBodyWrapper implements TemplateDirectiveBody, TemplateModel {

    private TemplateDirectiveBody body;
    private OverrideBodyWrapper parentBody;
    private Environment env;

    public OverrideBodyWrapper(TemplateDirectiveBody body, Environment env) {
        super();
        this.body = body;
        this.env = env;
    }

    public void render(Writer out) throws TemplateException, IOException {
        if (body == null)
            return;
        OverrideBodyWrapper preOverridy = (OverrideBodyWrapper) env
                .getVariable(FreemarkerSupports.OVERRIDE_CURRENT_NODE);
        try {
            env.setVariable(FreemarkerSupports.OVERRIDE_CURRENT_NODE, this);
            body.render(out);
        } finally {
            env.setVariable(FreemarkerSupports.OVERRIDE_CURRENT_NODE, preOverridy);
        }
    }

    public OverrideBodyWrapper getParentBody() {
        return parentBody;
    }

    public void setParentBody(OverrideBodyWrapper parentBody) {
        this.parentBody = parentBody;
    }
}
